<?php

class file {
    /**
     * File name
     * @var string 
     */
    var $name       = '';
    
    /**
     * MIME Type
     * @var string
     */
    var $mime       = '';
    
    /**
     * Extension
     * @var string
     */
    var $extension  = '';
    
    /**
     * Temp name
     * @var string
     */
    var $tmp_name   = '';
    
    /**
     * Error code
     * @var int
     */
    var $error      = UPLOAD_ERR_NO_FILE;
    
    /**
     * File size (byte)
     * @var int
     */
    var $size       = 0;
}

/**
 * Convert size(Kb,mb...) to size in byte
 * @deprecated Use parse_byte()
 * @param string $v_size
 * @return int 
 */
function namhoa_size_to_byte($v_size) {
    return parse_byte($v_size);
}

/**
 * Convert size(Kb,mb...) to size in byte
 * @param string $v_size
 * @return int 
 */
function parse_byte($v_size) {
    $a_powers = array(
        'K'     => 10,
        'M'     => 20,
        'G'     => 30,
        'T'     => 40,
        'P'     => 50,
        'E'     => 60,
        'Z'     => 70,
    );
    
    $a_match = array();
    
    if(preg_match('/^([0-9.,]+)\s?('.implode('|', array_keys($a_powers)).')?B?$/', $v_size, $a_match)) {
        $v_size   = floatval($a_match[1]);
        $v_prefix = $a_match[2];
        
        if($v_prefix == '') {
            return intval($v_size);
        }
        
        return intval($v_size * pow(2, $a_powers[$v_prefix]));
    }
    
    return -1;
}

function parse_file($f_files) {    
    if(!isset($f_files['name']) || !isset($f_files['type']) || !isset($f_files['tmp_name']) || !isset($f_files['error']) || !isset($f_files['size'])) {
        // Return empty file
        return new file();
    }
    
    $a_result   = null;
    
    if(is_array($f_files['name'])) {
        $a_result = array();
        
        foreach($f_files['name'] as $idx => $f_file) {
            $o_file             = new file();
            $o_file->name       = $f_files['name'       ][$idx];
            $o_file->mime       = $f_files['type'       ][$idx];
            $o_file->tmp_name   = $f_files['tmp_name'   ][$idx];
            $o_file->error      = $f_files['error'      ][$idx];
            $o_file->size       = $f_files['size'       ][$idx];
            $o_file->extension  = namhoa_filetype($o_file->name);

            $a_result[$idx] = $o_file;
        }
    }
    else {
        $o_file             = new file();
        $o_file->name       = $f_files['name'       ];
        $o_file->mime       = $f_files['type'       ];
        $o_file->tmp_name   = $f_files['tmp_name'   ];
        $o_file->error      = $f_files['error'      ];
        $o_file->size       = $f_files['size'       ];
        $o_file->extension  = namhoa_filetype($o_file->name);
        
        $a_result = $o_file;
    }
    
    return $a_result;
}

/**
* Copy file $v_source_file from directory $v_source_dir to directory $v_target_dir
* @param string $v_source_file
* @param string $v_source_dir
* @param string $v_target_dir
* @return boolean
*/
function namhoa_copyfile($v_source_file, $v_source_dir, $v_target_dir) {
    if (file_exists($v_source_dir . $v_source_file) && is_dir($v_target_dir)) {
        return copy($v_source_dir . $v_source_file, $v_target_dir . $v_source_file);
    }

    return false;
}

/**
* Check extension of file $v_filename is an extension in $v_target which is a string with extensions are divided by | 
* @param string $v_filename
* @param string $v_target
* @return boolean 
*/
function namhoa_checkfiletype($v_filename, $v_target) {
    $a_target   = explode('|', $v_target);
    $a_file     = explode('.', $v_filename);

    if(!in_array($a_file[count($a_file) - 1], $a_target)) {
        return false;
    }

    return true;
}

/** 
* Upload file $v_file['tmp_name'] to directory $v_dir,if $v_dir not exist,it will create new
* @param string $v_dir
* @param string $v_file 
*/
function namhoa_uploadfile($v_dir, $v_file) {
    namhoa_makedir($v_dir);
    move_uploaded_file($v_file['tmp_name'], $v_dir . $v_file['name']);
}

function namhoa_uploadfiles($f_files, $s_File_Path, $v_insertdate, $v_filetype = '', &$a_rows = array()) {
    if (!isset($f_files['name'])) { raise_error('Could NOT found selected files.');}

    $v_total = 1;

    if(is_array($f_files['name'])) {
        $v_total = count($f_files['name']);
    }
    else {
        $f_file['name'][0]     = $f_files['name'];
        $f_file['tmp_name'][0] = $f_files['tmp_name'];

        $f_files = $f_file;
    }

    if ($f_files['name'][0] == '' && $v_total == 1) { return;}

    $s_File_Path = $s_File_Path . substr($v_insertdate, 0, 7) . '/';
    if (!namhoa_makedir($s_File_Path)) { raise_error('Could NOT make directory.');}

    for ($i = 0; $i < $v_total; $i++) {
        if ($f_files['name'][$i] != '') {

            $v_filename = namhoa_filename($f_files['name'][$i]);

            $v_filename = str_replace(' ', '_', $v_filename);
            $v_filename = str_replace('"', '_', $v_filename);
            $v_filename = str_replace("'", '_', $v_filename);
            $v_filename = str_replace('.', '_', $v_filename);

            //$v_filesize     = namhoa_filesize(filesize($f_files['tmp_name'][$i]));
            $v_filesize     = format_byte(filesize($f_files['tmp_name'][$i]));
            $v_fileextension= namhoa_filetype($f_files['name'][$i]);
            $v_fileextension= strtolower($v_fileextension);

            $a_typerejects  = array('htm', 'html', 'shtml', 'php', 'php3', 'php4', 'phtml', 'inc', 'pl', 'cgi');

            if($v_fileextension == 'docx' || $v_fileextension == 'pptx' || $v_fileextension == 'xlsx') {
                raise_error('Formats: .docx, .pptx, .xlsx cannot up uploaded.\nPlease use .doc, .ppt or .xls.');
            }
            if (in_array($v_fileextension, $a_typerejects)) {
                $v_fileextension = 'txt';
            }

            $f_filename = $v_filename . '.' . $v_fileextension;

            $j = 1;

            while (file_exists($s_File_Path . $f_filename)) {
                $v_filename = $v_filename . '_' . $j;
                $f_filename = $v_filename . '.' . $v_fileextension;
                $j++;
            }

            $a_rows[] = array(
                'filestatus'    => 'ALLOWED'        ,
                'filetype'      => $v_filetype      ,
                'filename'      => $f_filename      ,
                'filesize'      => $v_filesize      ,
                'fileextension' => $v_fileextension ,
            );

            $f_file['name']     = $f_filename;
            $f_file['tmp_name'] = $f_files['tmp_name'][$i];

            if (!namhoa_uploadfile($s_File_Path, $f_file)) { 
                //raise_error('Could NOT upload.');                
            }                
        }
    }
}

/**
* Rename file
* @param string $v_source_dir
* @param string $v_source_file
* @param string $v_rename_dir
* @param string $v_rename_file
* @return boolean 
*/
function namhoa_renamefile($v_source_dir, $v_source_file, $v_rename_dir, $v_rename_file) {
    if(file_exists($v_source_file)) {
        if (!is_dir($v_rename_dir)) {
            namhoa_makedir($v_rename_dir);
        }

        return rename($v_source_dir . $v_source_file, $v_rename_dir . $v_rename_file);
    }

    return false;
}

/**
* Read file
* @param file $v_filename
* @return string 
*/
function namhoa_readfile($v_filename) {
    if(!file_exists($v_filename)) {
        return;
    }

    $v_filesize = file_size($v_filename);

    if($v_filesize < 1) {
        return;
    }

    if(function_exists('file_get_contents')) {
        return file_get_contents($v_filename);
    }

    $v_fp   = fopen($v_filename, 'r');
    $v_buff = '';

    if($v_fp) {
        while(!feof($v_fp) && strlen($v_buff) <= $v_filesize){
            $v_string   = fgets($v_fp, 1024);
            $v_buff    .= $v_string;
        }

        fclose($v_fp);
    }

    return $v_buff;
}

/**
* Write file
* @param string $v_filename
* @param string $v_buff
* @param string $v_mode
* @return bool  
*/
function namhoa_writefile($v_filename, $v_buff, $v_mode = 'w') {
    $v_pathinfo = pathinfo($v_filename);
    $v_path     = $v_pathinfo['dirname'];

    if(!is_dir($v_path)) {
        namhoa_makedir($v_path);
    }

    $v_mode = strtolower($v_mode);

    if($v_mode != 'a') {
        $v_mode = 'w';
    }

    if(@!$v_fp = fopen($v_filename, $v_mode)) {
        return false;
    }

    fwrite($v_fp, $v_buff);
    fclose($v_fp);
}

/**
 * Convert size in byte to other: KB,MB,GB...
 * @param  int      $v_size
 * @return string 
 */
function format_byte($v_size) {
    if($v_size < pow(1024, 1)) {
        return  $v_size.' Bytes';
    }
    else if($v_size < pow(1024, 2)) {
        return round($v_size/pow(1024, 1), 3).' KB';
    }
    else if($v_size < pow(1024, 3)) {
        return round($v_size/pow(1024, 2), 3).' MB';
    }
    else if($v_size < pow(1024, 4)) {
        return round($v_size/pow(1024, 3), 3).' GB';
    }
    else if($v_size < pow(1024, 5)) {
        return round($v_size/pow(1024, 4), 3).' TB';
    }
    else if($v_size < pow(1024, 6)) {
        return round($v_size/pow(1024, 5), 3).' PB';
    }
    else if($v_size < pow(1024, 7)) {
        return round($v_size/pow(1024, 6), 3).' EB';
    }
    else if($v_size < pow(1024, 8)) {
        return round($v_size/pow(1024, 7), 3).' ZB';
    }
    else {
        return round($v_size/pow(1024, 8), 3).' YB';
    }
}

/**
* Remove file
* @param string $v_dir 
*/
function namhoa_removefile($v_dir) {
    if(file_exists($v_dir)) {
        @unlink($v_dir);
    }

    $a_files  = array ();
    $s_folder = explode('/', $v_dir);

    unset($s_folder[count($s_folder) - 1]);

    $s_folder = implode('/', $s_folder);

    if ($v_fp = opendir($s_folder) ) {
        while ( false !== ( $v_file = readdir($v_fp) ) ) {
            if ($v_file != '.' && $v_file != '..') {
                $a_files[] = $v_file;
            }
        }

        closedir($v_fp);
    }

    if(!count($a_files)) {
        namhoa_removedir($s_folder);
    }
}

/**
* Remove extension of file
* @param string $v_filename
* @return string 
*/
function namhoa_filename($v_filename) {
    $v_filename = explode('.', $v_filename);
    unset($v_filename[count($v_filename) - 1]);

    return implode('.', $v_filename);
}

/**
* Convert size in byte to other: KB,MB,GB...
* @deprecated Use format_byte()
* @param int $v_filesize
* @return string 
*/
function namhoa_filesize($v_filesize) {
    return format_byte($v_filesize);
}

/**
* Get extension of file
* @param string $v_filename
* @return string 
*/
function namhoa_filetype($v_filename) {
    $a_filetype    = explode('.', $v_filename);
    $v_count_parts = count($a_filetype);

    return $v_count_parts == 1 ? '' : strtolower($a_filetype[$v_count_parts - 1]);
}

/**
* Create new directory name $v_dir
* @param string $v_dir
* @return bool 
*/
function namhoa_makedir($v_dir) {
    $a_dir      = explode('/', $v_dir);
    $v_count    = count($a_dir);
    $v_string   = '';

    if(substr($v_dir, 0, 1) == '/'){
        $v_string = '/';
    }

    for($i = 0; $i < $v_count; $i++){
        if($a_dir[$i] === '') {
            continue;
        }

        $v_string .= $a_dir[$i] . '/';
        
        if(!is_dir($v_string)){            
            @mkdir($v_string);
        }
    }

    return is_dir($v_dir);
}

/**
* Remove directory
* @param string $v_dir   
*/
function namhoa_removedir($v_dir) {
    if(!is_dir($v_dir)) {
        return;
    }

    $v_directory = dir($v_dir);

    while($v_entry  = $v_directory->read()) {
        if ($v_entry != '.' && $v_entry != '..') {
            if (is_dir($v_dir . '/' . $v_entry)) {
                namhoa_removedir($v_dir . '/' . $v_entry);
            }
            else {
                namhoa_removefile($v_dir . '/' . $v_entry);
            }
        }
    }

    $v_directory->close();
    @rmdir($v_dir);
}

/**
* Get path size
* @param string $v_path   
* @return path size 
*/
function get_dir_size($v_path) {
    $v_proc = popen('du -s --block-size=1 ' . $v_path, 'r');
    $v_size = fgets($v_proc, 4096);
    $v_size = (int) $v_size;
    pclose($v_proc);

    return $v_size;
}

/**
* Export file
* @param sring|resource    $v_fh           File path or File pointer
* @param string            $v_filename     File name
* @param string            $v_mode         Export mode, inline or attachment
*/
function export_file($v_fh, $v_filename, $v_mode = 'attachment') {
    // Make sure nothing was sent before
    if(@headers_sent()) {
        return false;
    }

    $v_open = false;

    // Support both file path and file pointer
    if(is_string($v_fh)) {
        $v_fh   = @fopen($v_fh, 'rb');
        $v_open = true;

        if(!$v_fh) {
            return false;
        }
    }
    else if(is_resource($v_fh) && get_resource_type($v_fh) == 'file') {
        fseek($v_fh, 0);
    }
    else {
        // Does not support
        return false;
    }

    @session_commit(); // Force close session    
    ob_start();

    while($v_stream = @fread($v_fh, 8192)) {
        echo $v_stream;
    }

    $v_filesize     = ob_get_length();
    $v_filecontent  = ob_get_clean();

    if($v_open) {
        @fclose($v_fh);
    }

    include 'lib_mimetype.php';

    $v_fileext      = namhoa_filetype($v_filename);
    $v_filemime     = namhoa_get_mime_type($v_fileext, $a_mimetypes);

    header('Content-Disposition: ' . $v_mode . '; filename="' . $v_filename . '"');
    header('Content-Transfer-Encoding: binary');
    //header('Accept-Ranges: bytes'); // Currently we do NOT support resume
    header('Content-Length: ' . $v_filesize);
    header('Connection: close');
    header('Content-Type: ' . $v_filemime);

    echo $v_filecontent;
    exit(0);
}

function create_image_file($v_sourcefile, $v_targetfile, $v_resize_width = 0, $v_resize_height = 0, $v_targettype = '', $v_thumbnail_type = 1) {

    if (!file_exists($v_sourcefile)){
        return;
    }
    list($v_width, $v_height, $v_type, $v_attrs) = @getimagesize($v_sourcefile);

    if (!$v_resize_width){
        $v_resize_width = $v_width;
    }
    if (!$v_resize_height){
        $v_resize_height = $v_height;
    }

    if ($v_width < 1 || $v_height < 1){
        return;
    }

    switch ($v_type) {
        case '1' :
            $v_type = 'gif';
            break;
        case '2' :
            $v_type = 'jpg';
            break;
        case '3' :
            $v_type = 'png';
            break;
        case '6' :
            $v_type = 'bmp';
            break;
        default :
            return;
            break;
    }
    
    if ($v_width < $v_resize_width){
        $v_resize_width = $v_width;
    }
    if ($v_height < $v_resize_height){
        $v_resize_height = $v_height;
    }
    if ($v_resize_width > 0 && $v_width >= $v_resize_width){
        $v_width_percentage = $v_resize_width / $v_width;
    }
    else {
        $v_width_percentage = $v_width / $v_resize_width;
    }

    if ($v_resize_height > 0 && $v_height >= $v_resize_height){
        $v_height_percentage = $v_resize_height / $v_height;
    }
    else{
        $v_height_percentage = $v_height / $v_resize_height;
    }

    if ($v_thumbnail_type == 3) {
        if ($v_width_percentage > $v_height_percentage) {
            $v_percentage = $v_height_percentage;
        }
        else {
            $v_percentage = $v_width_percentage;
        }
        $v_resize_width = $v_width * $v_percentage;
        $v_resize_height= $v_height * $v_percentage;
    }
    else {
        if ($v_width_percentage < $v_height_percentage) {
            $v_percentage = $v_height_percentage;
        }
        else {
            $v_percentage = $v_width_percentage;
        }
    }

    if (!$v_percentage) {
        $v_percentage = 1;
    }

    $v_type = strtolower($v_type);

    if (!$v_targettype){
        $v_targettype   = $v_type;
    }
    else {
        $v_targettype   = strtolower($v_targettype);
        $v_targetfile   = namhoa_filename($v_targetfile) . '.' . $v_targettype;
    }
    
    if (function_exists('imagecreatetruecolor')) {
        $v_thumbnail = @imagecreatetruecolor($v_resize_width, $v_resize_height);
    }
    else {
        $v_thumbnail = @imagecreate($v_resize_width, $v_resize_height);
    }

    $v_white = @imagecolorallocate($v_thumbnail, 255, 255, 255);
    
    @imagefilledrectangle($v_thumbnail, 0, 0, $v_resize_width - 1, $v_resize_height - 1, $v_white);

    switch ($v_type) {
        case 'gif' :
            $v_source = @imagecreatefromgif($v_sourcefile);
            break;
        case 'jpeg':
        case 'jpg' :
            $v_source = @imagecreatefromjpeg($v_sourcefile);
            break;
        case 'png' :
            $v_source = @imagecreatefrompng($v_sourcefile);
            break;
        case 'wbmp':
        case 'bmp' :
            $v_source = @imagecreatefromwbmp($v_sourcefile);
            break;
        default :
            return;
    }
    
    $v_path = preg_replace('/\/([^\.^\/]*)\.(gif|png|jpg|jpeg|bmp|wbmp)$/i', '', $v_targetfile);
    if(!is_dir($v_path))
    {
        namhoa_makedir($v_path);
    }
    
    $v_new_width    = $v_width * $v_percentage;
    $v_new_height   = $v_height * $v_percentage;
    
    $v_new_width    = intval($v_new_width);
    $v_new_height   = intval($v_new_height);
    
    if ($v_thumbnail_type == 2) {
        $x = $v_resize_width/2 - $v_new_width/2;
        $y = $v_resize_height/2 - $v_new_height/2;

        $x = intval($x);
        $y = intval($y);
    }
    else {
        $x = 0;
        $y = 0;
    }

    if ($v_source) {
        if (function_exists('imagecopyresampled')) {
            @imagecopyresampled($v_thumbnail, $v_source, $x, $y, 0, 0, $v_new_width, $v_new_height, $v_width, $v_height);
        }
        else {
            @imagecopyresized($v_thumbnail, $v_source, $x, $y, 0, 0, $v_new_width, $v_new_height, $v_width, $v_height);
        }
    }
    
    switch ($v_targettype) {
        case 'gif' :
            @imagegif($v_thumbnail, $v_targetfile, 100);
            break;
        case 'jpeg':
        case 'jpg' :
            @imagejpeg($v_thumbnail, $v_targetfile, 100);
            break;
        case 'png' :
            @imagepng($v_thumbnail, $v_targetfile, 9);
            break;
        case 'wbmp':
        case 'bmp' :
            @imagewbmp($v_thumbnail, $v_targetfile, 100);
            break;
    }
}
?>